﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       MesHelperSharp
- 机器名称：       YTE
- 命名空间：       LD.Tool.MES.sharp
- 文 件 名：       MesHelperSharp
- 创建时间：       2022/7/31 19:45:25
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using LD.Host;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;

namespace LD.Tool
{
    [Tool(Text = "TcpIp", FrmParam = "ToolTcpIpFrm", ToolType = ToolEnum.通讯)]

    public class ToolTcpIp : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    var param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolTcpIpParam>(model.Param);
                    if (param.SplitChart)
                        param.Cmd = param.Cmd + "\r";
                    string res = CommunicateFactory.Instance.TcpIp[param.TcpIpName].Send(param.Cmd, param.TimeOut);
                    Log(model, $"返回:【{res}】", LogLevel.一般);
                    //= CommunicateFactory.Instance.TcpIp[param.TcpIpName].Receive(param.TimeOut);
                    if (param.NotNullResult && string.IsNullOrEmpty(res))
                        isSuccess = false;
                    else
                    {
                        if (param.IsThanResult)
                        {
                            if (param.ThanResult.Equals(res.Trim()))
                                isSuccess = true;
                            else
                            {
                                isSuccess = false;
                            }
                        }
                        else
                            isSuccess = true;
                    }

                    if (isSuccess && param.IsSaveResult)
                    {
                        var result = (List<Variable>)Cache.GetCache(CONST.VARIABLE);
                        if (result != null && result.Count > 0)
                        {
                            var val = result.Where(p => p.Name == param.SaveResult).FirstOrDefault();
                            if (val != null)
                            {
                                val.Val = res;
                                Cache.SaveCache();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
    }
}
